<?php
/**
 * 《交易信息》实现类
 *
 * @author 孙晓晔
 * @version $Id: Country.class.php 832 2010-01-06 09:17:14Z xuy $
 */

require_once(dirname(__FILE__) . '/FinanceUtil.class.php');

class Transaction extends FinanceUtil {
	public $tbl = Constant::tbl_cw_transaction;
	
	public $type = array(
		'-' => '请选择',
		'1' => '收入',
							
		'2' => '借款',			
		'3' => '还款',
		'4' => '退款',		
		'5' => '代收',
		'6' => '利息',
		
		'9' => '其它',
	);
	
	public $bank = array(
		'-' => '请选择',
		'1' => '现金',
		'2' => '招商银行',
		'3' => '兴业银行',
		'4' => '中国民生银行',
		'5' => '中国建设银行',
		'6' => '中信银行',

		'9' => '其它',
	);
	
	public $share = array(
		'-' => '请选择',
		'1' => '共享',
		'2' => '不共享',

		'9' => '其它',
	);
	
	public $status = array(
		'-' => '请选择',
		'1' => '等待到帐',
		'2' => '已经到帐',
		'3' => '正在确认',
		'4' => '完成确认',

		'9' => '其它',
	);
	
	public $orderby = array(
		'-' => '请选择',
		'emp' => '业务员',
		'customer' => '客户',
		'payment' => '方式',
		'rmb' => '金额',
		'date' => '到帐日期',

		'1' => '创建时间',
		'2' => '更新时间',
	);
	
	public $groupby = array(
		'-' => '请选择',
		
		'office' => '办公区',
		'bank' => '银行',
		'account' => '帐户',
			
		'customer' => '客户',
		'emp' => '业务员',
		'payment' => '方式',
		'currency' => '币种',
	
		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
		
		$controller->assign_by_ref('type_option', $this->type);
		$controller->assign_by_ref('bank_option', $this->bank);
		
		$controller->assign_by_ref('share_option', $this->share);
	}
	
	function tab($controller, $request) {		
		$data = array(
			'银行到帐' => array('cc'=>'finance.php?do=Transaction.find', 'js'=>'1'),
			'开票信息' => array('cc'=>'finance.php?do=Invoice.find', 'js'=>'1'),
			'收入信息' => array('cc'=>'finance.php?do=In.find', 'js'=>'1'),
		    '收入明细' => array('cc'=>'finance.php?do=InItem.find', 'js'=>'1'),
			
			'提成信息' => array('cc'=>'finance.php?do=Commission.find', 'js'=>''),		    
			'客户信息' => array('cc'=>'contact.php?do=FinanceCustomer.find', 'js'=>''),
		
			'支出信息' => array('cc'=>'finance.php?do=Out.find', 'js'=>'1'),
		    '支出明细' => array('cc'=>'finance.php?do=OutItem.find', 'js'=>'1'),
			
			'统计分析' => array('cc'=>'finance.php?do=Transaction.tj_tab', 'js'=>''),
		);
		
		$ret = $this->_tab($data);

		$controller->assign_by_ref('result', $ret);

		$controller->display($request, 'tab');
		return true;
	}
	
	function tj_tab($controller, $request) {		
		$data = array(
			'银行到帐' => array('cc'=>'finance.php?do=Transaction.group', 'js'=>''),
			'开票信息' => array('cc'=>'finance.php?do=Invoice.group', 'js'=>''),
			'提成信息' => array('cc'=>'finance.php?do=Commission.group', 'js'=>''),
			
			'收入信息' => array('cc'=>'finance.php?do=In.group', 'js'=>''),
			'收入明细' => array('cc'=>'finance.php?do=InItem.group', 'js'=>''),
		
			'付款信息' => array('cc'=>'finance.php?do=Payment.group', 'js'=>''),
			'支出信息' => array('cc'=>'finance.php?do=Out.group', 'js'=>''),
			'支出明细' => array('cc'=>'finance.php?do=OutItem.group', 'js'=>''),	
		);
		
		$ret = $this->_tab($data);

		$controller->assign_by_ref('result', $ret);

		$controller->display($request, 'tj_tab');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-3 month'));
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '业务员',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);
		
		$controller->display($request, 'finance/transaction/find');
		return true;
	}
	
	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == 'mobile') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['mobile'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {	
		$type_s = $request['type_s'];
		
		$bank_s = $request['bank_s'];		
		$account_s = $request['account_s'];
		
		$payment_s = $request['payment_s'];		
		$detail_s = $request['detail_s'];
				
		$date1_s = $request['date1_s'];
		$date2_s = $request['date2_s'];
		
		$share_s = $request['share_s'];
		
		$emp_t_s = $request['emp_t_s'];
		if ($emp_t_s == 'emp') {
			$request['emp_s'] = $request['emp_a_s'];
		} else if ($emp_t_s == 'oper') {
			$request['oper_s'] = $request['emp_a_s'];
		}

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}
		
		$where .= $this->_where_x("bank", $request['bank_s']);
		$where .= $this->_where_x("account", $request['account_s']);
		
		if (!empty($type_s) && $type_s <> '-') {
			$where .= " AND type = '" . $type_s . "'";
		}
		
		if (!empty($detail_s)) {
			$where .= " AND detail LIKE '%" . $detail_s . "%'";
		}
				
		if (!empty($payment_s) && $payment_s <> '-') {
			$where .= " AND payment = '" . $payment_s . "'";
		}
		
		if (!empty($date1_s)) {
			$where .= " AND date >= '" . $date1_s . "'";
		}

		if (!empty($date2_s)) {
			$where .= " AND date < '" . $date2_s . "'";
		}
		
		if (!empty($share_s) && $share_s <> '-') {
			$where .= " AND share = '" . $share_s . "'";
		}
		
		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}

		$emp = $_SESSION['id'];
		
		$p = array('1'=>'161', '2'=>'162', '3'=>'173');
		
		$a = $this->_audit_office($p);
		if (count($a) > 0) {
			$office = implode(",", $a);
			
			return sprintf(" visible = 1 AND ((share = '1' AND office in (%s)) OR emp = '%s' OR oper = '%s')", $office, $emp, $emp);
		}	

		return sprintf(" visible = 1 AND (share = '1' OR emp = '%s' OR oper = '%s')", $emp, $emp);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);
				// $row['num_'] = $this->_num($row['id']);
				$row['abc'] = $this->_in_item2($row['id']);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		} else {
			$controller->clear_assign('result');
		}

		$controller->display($request, 'finance/transaction/list');
		return true;
	}
	
	function _num($id) {
		$ret = $this->_in_item($id);
		
		return count($ret);
	}
	
	function _in_item($id, $status = 'all') {
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();
		
		return $aa->_list_transaction($id);
	}
	
	function _in_item2($id, $status = 'all') {
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();		
		
		$data = $aa->_list_transaction($id);
		$ret = array("a" => 0, "n" => 0);
		while (list($k, $v) = each($data)) {
			$ret['a'] += $v['amount'];
			$ret['n']++;
		}
		
		return $ret;
	}
	
	function xls($controller, $request) {
		$this->pretreat($controller);
		
		$this->findPara($controller, $request);

		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s LIMIT 20";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$row = $this->_orderby_x($controller, $row, $this->orderby_s);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'finance/transaction/list');
		return true;
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 day'));

		$controller->display($request, 'finance/transaction/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$customer = $this->_input($request['customer']);
		$customer_x = addslashes($request['customer_x']);
		
		$type = $request['type'];
		$bank = $request['bank'];
		$account = $request['account'];
		
		$date = $request['date'];
		$share = $request['share'];
		
		$currency = $request['currency'];
		
		$remittance = $request['remittance'];
		$fee = $request['fee'];
				
		$total = $request['total'];
		$amount = $request['amount'];
		$kc = $request['kc'];
		
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$detail = addslashes($request['detail']);
		$content = addslashes($request['content']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, customer, customer_x, type, bank, account, date, currency, remittance, fee, total, amount, kc, rate, rmb, detail, content, share, emp, oper";
		$fmt .= ", createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $office, $customer, $customer_x, $type, $bank, $account, $date, $currency, $remittance, $fee, $total, $amount, $kc, $rate, $rmb, $detail, $content, $share, $emp, $_SESSION['id']);
		debug($sql);
		$db->query($sql);
		
		$request['id_s'] = $db->insert_id();

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function upload($controller, $request) {
		$this->pretreat($controller);
	
		$id = $request['id'];
		
		$this->_files_clean($id);
		
		$row = $this->_view($id);
		
		$row['files'] = $this->_files($row['id']);
	
		$controller->assign_by_ref('result', $row);
	
		$controller->display($request, 'finance/transaction/upload');
		return true;
	}
	
	function copy($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/transaction/copy');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/transaction/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$customer = $this->_input($request['customer']);
		$customer_x = addslashes($request['customer_x']);
		
		$type = $request['type'];
		$bank = $request['bank'];
		$account = $request['account'];
		
		$date = $request['date'];
		$share = $request['share'];
		
		$currency = $request['currency'];
		
		$remittance = $request['remittance'];
		$fee = $request['fee'];
		
		$total = $request['total'];
		$amount = $request['amount'];
		$kc = $request['kc'];
		
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$detail = addslashes($request['detail']);
		$content = addslashes($request['content']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET office = '%s', customer = '%s', customer_x = '%s', type = '%s', bank = '%s', account = '%s', date = '%s', currency = '%s', remittance = '%s', fee = '%s', total = '%s', ";
		$fmt .= "amount = '%s', kc = '%s', rate = '%s', rmb = '%s', detail = '%s', content = '%s', share = '%s', emp = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $customer, $customer_x, $type, $bank, $account, $date, $currency, $remittance, $fee, $total, $amount, $kc, $rate, $rmb, $detail, $content, $share, $emp, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {		
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$row['files'] = $this->_files($row['id']);

		$controller->assign_by_ref('result', $row);
		
		$row['item'] = $this->_transaction_item($row['id']);

		$controller->display($request, 'finance/transaction/view');
		return true;
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('310');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '银行到帐';
	
		$cc = array(
			'到帐信息'=>array('w' => "DATE_FORMAT(date, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}

		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'finance/transaction/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function tjw($controller, $request) {
		$bb = $this->_list_email('310');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '银行到帐（周报）';
	
		$cc = array(
			'到帐信息'=>array('w' => "DATE_FORMAT(date, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'finance/transaction/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
		
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'currency';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, SUM(amount*rate) AS c, SUM(amount) AS d FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, SUM(amount*rate) AS c, SUM(amount) AS d FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
	
	function _transaction_item($id, $status = 'all') {
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();
		
		return $aa->_list_transaction($id);
	}

	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['customer_t'] = Name::customer_code($row['customer']);
		$row['customer_x'] = json_decode($row['customer_x']);
		// $row['supplier_x'] = $row['customer_x'];
		
		$row['type_t'] = $this->type[$row['type']];
		$row['bank_t'] = $this->bank[$row['bank']];
		
		$row['account_t'] = $this->account[$row['account']];
		
		$row['payment_t'] = $this->payment[$row['payment']];
		$row['share_t'] = $this->share[$row['share']];
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function _list($emp) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE emp = '%s' AND status = '3' ORDER BY id";
		$sql = sprintf($fmt, $this->tbl, $emp);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row['ok'] = true;			

			$ret[] = $row;
		}

		return $ret;
	}
	
	function _list_3($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE customer = '%s' ORDER BY id DESC LIMIT 20";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$ret[] = $row;
		}
		
		return $ret;
	}
	
	function verify($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/transaction/verify');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function verifyPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$content = addslashes($request['content']);
		$status = $request['status'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET content = concat(content, '%s'), status = '%s', modifytime = now() WHERE id = %s";
		$sql = sprintf($fmt, $this->tbl, $content, $status, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function arrive($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		$email = array(
			'-' => '请选择',
			'1' => '是',		
			'2' => '否',
		);
		$controller->assign_by_ref('email_option', $email);

		$controller->display($request, 'finance/transaction/arrive');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function arrivePost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		
		$email = $request['email'];
		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET content = concat(content, '\n%s'), status = '2', modifytime = now() WHERE id = %s";
		$sql = sprintf($fmt, $this->tbl, $content, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}
		
		$row = $this->_view($id);
		if ($email == '1') {			
			$from = $_SESSION['id'];
	
			$to = $row['emp'];
			// $to = "101";
			$row['to'] = Name::emp($to);
	
			$controller->assign_by_ref('result', $row);
			
			$subject = sprintf('银行到帐 %s', $row['id']);
			$body = $controller->sunxy($request, 'finance/transaction/body_2');
			debug($body);
			
			$this->_notice($from, $to, $subject, $body, 1);
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function finish($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$row['item'] = $this->_transaction_item($row['id']);

		$controller->assign_by_ref('result', $row);
		
		$email = array(
			'-' => '请选择',
			'1' => '是',		
			'2' => '否',
		);
		$controller->assign_by_ref('email_option', $email);

		$controller->display($request, 'finance/transaction/finish');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function finishPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		
		$email = $request['email'];
		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET content = concat(content, '\n%s'), status = '4', modifytime = now() WHERE id = %s";
		$sql = sprintf($fmt, $this->tbl, $content, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}
		
		$this->_in_item_finish($id);
		
		$row = $this->_view($id);
		if ($email == '1') {			
			$from = $_SESSION['id'];
	
			$to = $row['emp'];
			// $to = "101";
			$row['to'] = Name::emp($to);
			
			$row['item'] = $this->_transaction_item($row['id']);
	
			$controller->assign_by_ref('result', $row);
			
			$subject = sprintf('款项确认 %s', $row['id']);
			$body = $controller->sunxy($request, 'finance/transaction/body_4');
			debug($body);
			
			$this->_notice($from, $to, $subject, $body, 1);
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _in_item_finish($id) {
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();
	
		$aa->_update_finish($id);
	}
	
	function group($controller, $request) {
		$this->pretreat_group($controller);

		// $controller->assign('t1', strtotime('-3 month'));
		
		$num = array(
			'1' => '按次数',
			'2' => '按到帐金额',
			'3' => '按扣除费用',
			'4' => '按人民币',
		);
		$controller->assign('num_option', $num);

		$controller->display($request, 'finance/transaction/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'currency');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function groupby_dd($px) {
		if ($px == '1') {
			return "DATE_FORMAT(date, '%Y-%m-%d %H')";
		}

		if ($px == '2') {
			return "DATE_FORMAT(date, '%Y-%m-%d')";
		}

		if ($px == '3') {
			return "DATE_FORMAT(date, '%Y-%m')";
		}

		return $px;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$num_s = $request['num_s'];
		if ($num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(amount) AS c FROM %s a ";
		} else if ($num_s == '3') {
			$fmt = "SELECT %s AS a, SUM(kc) AS c FROM %s a ";
		} else if ($num_s == '4') {
			$fmt = "SELECT %s AS a, SUM(rmb) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(amount) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'currency') {
			$row['a'] = $this->currency[$row['a']];
		} elseif ($px == 'bank') {
			$row['a'] = $this->bank[$row['a']];
		} elseif ($px == 'account') {
			$row['a'] = $this->account[$row['a']];
		} elseif ($px == 'payment') {
			$row['a'] = $this->payment[$row['a']];
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}
	
	function _list_2($customer = '') {
		$db = newdb($this->dsn_r);
		if (!empty($customer)) {
			$fmt = "SELECT * FROM %s WHERE status IN (2, 3) AND customer = '%s'  ORDER BY id DESC";
			$sql = sprintf($fmt, $this->tbl, $customer);
		} else {
			$fmt = "SELECT * FROM %s WHERE status IN (2, 3) ORDER BY id DESC";
			$sql = sprintf($fmt, $this->tbl);
		}
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			// $ret[$row['id']] = $row['id'] . "/" . $row['customer_t'] . "/" . $row['amount'];
			$ret[] = $row;
		}
		
		return $ret;
	}
	
	function z($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE detail <> '' LIMIT 10";
		$fmt = "SELECT * FROM %s WHERE detail <> ''";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$s = $row['detail'];
			// echo $s;
			// echo $row['detail'] . "\n";
			if (preg_match("/(from)([\s|\S]+)(received)/i", $s, $m)) {
				// echo $s;
				// print_r($m);
				$ret['bank'] = trim($m[2]);
			}
			
			if (preg_match("/(By Order Of)([\s|\S]+)(In Favour of)/i", $s, $m)) {
				// echo $s;
				// print_r($m);
				$ret['name'] = trim($m[2]);
			}
			
			$item = $this->_transaction_item($row['id']);
			
			$ret['t1'] = 0;
			while (list($k, $v) = each($item)) {
				$ret['t1'] += $v['total'];
			}
			
			$ret['t2'] = $row['total'];
			$ret['amount'] = $row['amount'];
			$ret['k2'] = $row['kc'];
			$ret['k1'] = $ret['t1'] - $ret['t2'];			
			$ret['k'] = $ret['k1'] + $ret['k2'];	
			
			// print_r($ret);
			
			$fmt = "INSERT INTO ns.tt(xx, currency, name, bank, t1, t2, amount, k, k1, k2) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
			$sql = sprintf($fmt, $row['id'], $row['currency'], $ret['name'], $ret['bank'], $ret['t1'], $row['total'], $row['amount'], $ret['k'], $ret['k1'], $ret['k2']);
			echo $sql . "\n";
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}
		
	function _tj_a($controller, $request) {	
		$s = $this->groupby($controller, $this->groupby_s);
		$df = "DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')";

		$fmt = "SELECT %s as a, SUM(amount) as c FROM %s a WHERE date >= %s GROUP BY %s ORDER BY c DESC";
		$sql = sprintf($fmt, $s, $this->tbl, $df, $s);
		echo $sql . "\n";

		$this->_group_tj($controller, $sql);

		return $controller->sunxy($request, 'tj_a');
	}
	
	function remittance($controller, $request) {
		$this->pretreat($controller);
		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$remittance = $this->_remittance($row['id']);
			
			$fmt = "UPDATE %s SET remittance = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $remittance, $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function _remittance($id) {
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();
		
		$list = $aa->_list_transaction($id);
		$ret = 0;
		while (list($k, $v) = each($list)) {
			$ret += $v['total'];
		}
		
		return $ret;
	}
	
	function tj_rmb($controller, $request) {
		$this->pretreat($controller);

		require_once(dirname(__FILE__) . '/../contact/Customer.class.php');
		$aa = new Customer();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT customer AS a, SUM(rmb) AS c FROM %s GROUP BY customer";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$aa->_x_rmb($row['a'], $row['c']);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function star($controller, $request) {
		$this->pretreat($controller);
		
		$s = "DATE_FORMAT(date, '%Y-%m-%d') > DATE_FORMAT(DATE_ADD(now(), INTERVAL -180 DAY), '%Y-%m-%d')";
		
		require_once(dirname(__FILE__) . '/../contact/Customer.class.php');
		$aa = new Customer();
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT customer AS a, SUM(rmb) AS c FROM %s WHERE %s GROUP BY customer ORDER BY c DESC";
		$sql = sprintf($fmt, $this->tbl, $s);
		echo $sql . "\n";
		$result = $db->query($sql);
		$i = 1;
		while ($row = $db->fetch_array($result)) {
			$star = $this->_star($i++, $row['c']);
			
			$aa->_star($row['a'], $star);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function po($controller, $request) {
		$this->pretreat($controller);
		
		$dd = date('Y-m-d', strtotime("-2 MONTH"));
	
		$s = "DATE_FORMAT(date, '%Y-%m-%d') > DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')";
	
		require_once(dirname(__FILE__) . '/../contact/Customer.class.php');
		$aa = new Customer();
		$aa->_update_status_x("2", "3", $dd);
	
		$db = newdb($this->dsn_r);
		$fmt = "SELECT customer AS a, SUM(rmb) AS c FROM %s WHERE %s GROUP BY customer ORDER BY c DESC";
		$sql = sprintf($fmt, $this->tbl, $s);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {	
			$aa->_update_status($row['a'], '2');
		}
	
		logdate($controller, $request);
		return true;
	}
	
	function _star($i, $c) {
		if ($i < 10) {
			return 5;
		}
		
		if ($i < 20) {
			return 4;
		}
		
		if ($i < 30) {
			return 3;
		}
		
		if ($i < 40) {
			return 2;
		}
		
		return 1;
	}
	
	function move_id($customer, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE customer = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $customer);
		debug($sql);
		$db->query($sql);
	}
	
	function move($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
	
	function view_customer($controller, $request) {
		$id = $request['id'];
	
		$ret = $this->_list_customer($id);
	
		$controller->assign_by_ref('result', $ret);
	
		$controller->display($request, 'finance/transaction/_list_c');
		return true;
	}
}
?>